package com.ruoyi.report_jkdj.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.report_jkdj.domain.DjczlbgBaDetail;
import com.ruoyi.report_jkdj.domain.vo.DjczlbgBaDetailVo;
import com.ruoyi.report_jkdj.mapper.DjczlbgBaDetailMapper;
import com.ruoyi.syrw.annotation.ComputeReportResult;
import com.ruoyi.syrw.annotation.FIllBasicInfo;
import com.ruoyi.syrw.annotation.FIllBasicInfoForTaiZhang;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.report_jkdj.domain.bo.DjczlbgBsInfoBo;
import com.ruoyi.report_jkdj.domain.vo.DjczlbgBsInfoVo;
import com.ruoyi.report_jkdj.domain.DjczlbgBsInfo;
import com.ruoyi.report_jkdj.mapper.DjczlbgBsInfoMapper;
import com.ruoyi.report_jkdj.service.IDjczlbgBsInfoService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 地基承载力试验检测报告Service业务层处理
 *
 * @author zyb
 * @date 2024-07-25
 */
@RequiredArgsConstructor
@Service
@DSTransactional
public class DjczlbgBsInfoServiceImpl implements IDjczlbgBsInfoService {

    private final DjczlbgBsInfoMapper baseMapper;
    private final DjczlbgBaDetailMapper detailMapper;

    /**
     * 查询地基承载力试验检测报告
     */
    @Override
    @FIllBasicInfo
    public DjczlbgBsInfoVo queryById(Long excelId) {
        DjczlbgBsInfoVo djczlbgBsInfoVo = baseMapper.selectVoById(excelId);
        // 查询detail
        List<DjczlbgBaDetailVo> baDetailVos = detailMapper.selectVoList(new LambdaQueryWrapper<DjczlbgBaDetail>()
            .eq(DjczlbgBaDetail::getExcelId, excelId)
            .orderByAsc(DjczlbgBaDetail::getXuh));
        if (CollUtil.isNotEmpty(baDetailVos)) {
            djczlbgBsInfoVo.setBaDetailVos(baDetailVos);
        }
        // 如果已经有值了则不需要计算结论。
        if (StrUtil.isNotEmpty(djczlbgBsInfoVo.getJiancjl()) && !"检测结论：".equals(djczlbgBsInfoVo.getJiancjl())) {
            return djczlbgBsInfoVo;
        }
        return jcjl(djczlbgBsInfoVo);
    }

    @Override
    @FIllBasicInfoForTaiZhang
    public DjczlbgBsInfoVo queryByIdForTaizhang(Long excelId) {
        DjczlbgBsInfoVo djczlbgBsInfoVo = baseMapper.selectVoById(excelId);
        // 查询detail
        List<DjczlbgBaDetailVo> baDetailVos = detailMapper.selectVoList(new LambdaQueryWrapper<DjczlbgBaDetail>()
            .eq(DjczlbgBaDetail::getExcelId, excelId)
            .orderByAsc(DjczlbgBaDetail::getXuh));
        if (CollUtil.isNotEmpty(baDetailVos)) {
            djczlbgBsInfoVo.setBaDetailVos(baDetailVos);
            djczlbgBsInfoVo.setCedwz(baDetailVos.get(0).getJiancbw());

            List<DjczlbgBaDetailVo> collect = baDetailVos.stream()
                .filter(v -> BigDecimalUtil.isNotEmpty(v.getJiancjg()))
                .collect(Collectors.toList());

            // 计算 jiancjg 的总和
            BigDecimal sum = collect.stream()
                .map(DjczlbgBaDetailVo::getJiancjg)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

            // 计算平均值
            BigDecimal average = BigDecimalUtil.stpTrailZero(BigDecimalUtil.divide(sum, new BigDecimal(collect.size())));
            djczlbgBsInfoVo.setShicczl(BigDecimalUtil.toString(average));

        }
        // 如果已经有值了则不需要计算结论。
        if (StrUtil.isNotEmpty(djczlbgBsInfoVo.getJiancjl()) && !"检测结论：".equals(djczlbgBsInfoVo.getJiancjl())) {
            return djczlbgBsInfoVo;
        }
        return jcjl(djczlbgBsInfoVo);
    }

    /**
     * 查询地基承载力试验检测报告列表
     */
    @Override
    public TableDataInfo<DjczlbgBsInfoVo> queryPageList(DjczlbgBsInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DjczlbgBsInfo> lqw = buildQueryWrapper(bo);
        Page<DjczlbgBsInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询地基承载力试验检测报告列表
     */
    @Override
    public List<DjczlbgBsInfoVo> queryList(DjczlbgBsInfoBo bo) {
        LambdaQueryWrapper<DjczlbgBsInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DjczlbgBsInfo> buildQueryWrapper(DjczlbgBsInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DjczlbgBsInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTotalPage() != null, DjczlbgBsInfo::getTotalPage, bo.getTotalPage());
        lqw.eq(bo.getPage() != null, DjczlbgBsInfo::getPage, bo.getPage());
        lqw.eq(StringUtils.isNotBlank(bo.getBaogbh()), DjczlbgBsInfo::getBaogbh, bo.getBaogbh());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancdwmc()), DjczlbgBsInfo::getJiancdwmc, bo.getJiancdwmc());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcbwyt()), DjczlbgBsInfo::getGongcbwyt, bo.getGongcbwyt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpmc()), DjczlbgBsInfo::getYangpmc, bo.getYangpmc());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpbh()), DjczlbgBsInfo::getYangpbh, bo.getYangpbh());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpsl()), DjczlbgBsInfo::getYangpsl, bo.getYangpsl());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpzt()), DjczlbgBsInfo::getYangpzt, bo.getYangpzt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpsj()), DjczlbgBsInfo::getYangpsj, bo.getYangpsj());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpgg()), DjczlbgBsInfo::getYangpgg, bo.getYangpgg());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancrq()), DjczlbgBsInfo::getJiancrq, bo.getJiancrq());
        lqw.eq(StringUtils.isNotBlank(bo.getChucrq()), DjczlbgBsInfo::getChucrq, bo.getChucrq());
        lqw.eq(StringUtils.isNotBlank(bo.getJincrq()), DjczlbgBsInfo::getJincrq, bo.getJincrq());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjwd()), DjczlbgBsInfo::getShiytjwd, bo.getShiytjwd());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjsd()), DjczlbgBsInfo::getShiytjsd, bo.getShiytjsd());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyj()), DjczlbgBsInfo::getJiancyj, bo.getJiancyj());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyj()), DjczlbgBsInfo::getPandyj, bo.getPandyj());
        lqw.eq(StringUtils.isNotBlank(bo.getZhuyyqsbmcjbh()), DjczlbgBsInfo::getZhuyyqsbmcjbh, bo.getZhuyyqsbmcjbh());
        lqw.eq(StringUtils.isNotBlank(bo.getQuywz()), DjczlbgBsInfo::getQuywz, bo.getQuywz());
        lqw.eq(StringUtils.isNotBlank(bo.getWeitrwbh()), DjczlbgBsInfo::getWeitrwbh, bo.getWeitrwbh());
        lqw.eq(StringUtils.isNotBlank(bo.getTuycd()), DjczlbgBsInfo::getTuycd, bo.getTuycd());
        lqw.eq(StringUtils.isNotBlank(bo.getShengccj()), DjczlbgBsInfo::getShengccj, bo.getShengccj());
        lqw.eq(StringUtils.isNotBlank(bo.getPih()), DjczlbgBsInfo::getPih, bo.getPih());
        lqw.eq(StringUtils.isNotBlank(bo.getDaibsl()), DjczlbgBsInfo::getDaibsl, bo.getDaibsl());
        lqw.eq(StringUtils.isNotBlank(bo.getFujsm()), DjczlbgBsInfo::getFujsm, bo.getFujsm());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancjl()), DjczlbgBsInfo::getJiancjl, bo.getJiancjl());
        lqw.eq(StringUtils.isNotBlank(bo.getShigwtdw()), DjczlbgBsInfo::getShigwtdw, bo.getShigwtdw());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcmc()), DjczlbgBsInfo::getGongcmc, bo.getGongcmc());
        lqw.eq(StringUtils.isNotBlank(bo.getShebIds()), DjczlbgBsInfo::getShebIds, bo.getShebIds());
        lqw.eq(StringUtils.isNotBlank(bo.getBgFlag()), DjczlbgBsInfo::getBgFlag, bo.getBgFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyjIds()), DjczlbgBsInfo::getJiancyjIds, bo.getJiancyjIds());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyjIds()), DjczlbgBsInfo::getPandyjIds, bo.getPandyjIds());
        lqw.eq(bo.getShejczl() != null, DjczlbgBsInfo::getShejczl, bo.getShejczl());
        lqw.eq(StringUtils.isNotBlank(bo.getJisgs()), DjczlbgBsInfo::getJisgs, bo.getJisgs());
        lqw.eq(bo.getJisgsK() != null, DjczlbgBsInfo::getJisgsK, bo.getJisgsK());
        lqw.eq(bo.getJisgsB() != null, DjczlbgBsInfo::getJisgsB, bo.getJisgsB());
        lqw.eq(StringUtils.isNotBlank(bo.getImageUrl()), DjczlbgBsInfo::getImageUrl, bo.getImageUrl());
        return lqw;
    }

    /**
     * 新增地基承载力试验检测报告
     */
    @Override
    public Boolean insertByBo(DjczlbgBsInfoBo bo) {
        DjczlbgBsInfo add = BeanUtil.toBean(bo, DjczlbgBsInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setExcelId(add.getExcelId());
            // 新增详细 10
            ArrayList<DjczlbgBaDetail> details = new ArrayList<>(10);
            for (long i = 1; i <= 10; i++) {
                details.add(new DjczlbgBaDetail(add.getExcelId(), i));
            }
            detailMapper.insertBatch(details);
        }
        return flag;
    }

    /**
     * 修改地基承载力试验检测报告
     */
    @Override
    @ComputeReportResult
    public Boolean updateByBo(DjczlbgBsInfoBo bo) {
        // 增加对 是否合格 的填充
        fillExcelResult(bo);
        DjczlbgBsInfo update = BeanUtil.toBean(bo, DjczlbgBsInfo.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            detailMapper.updateBatchById(BeanUtil.copyToList(bo.getBaDetailVos(), DjczlbgBaDetail.class));
        }
        return flag;
    }

    private void fillExcelResult(DjczlbgBsInfoBo bo) {
        if (CollUtil.isNotEmpty(bo.getBaDetailVos())) {
            for (DjczlbgBaDetailVo detailVo : bo.getBaDetailVos()) {
                if ("不符合".equals(detailVo.getJiegpd())) {
                    bo.setExcelResult(2);
                    return;
                }
            }
            bo.setExcelResult(1);
            return;
        }
        bo.setExcelResult(0);
    }

    public boolean isWell(Long excelId) {
        return baseMapper.selectVoById(excelId).getExcelResult() != 2;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DjczlbgBsInfo entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除地基承载力试验检测报告
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 生成 地基承载力 报告 检测结论
     */
    @Override
    public DjczlbgBsInfoVo jcjl(DjczlbgBsInfoVo vo) {
//        if (StrUtil.isEmpty(vo.getPandyj())) {
//            return vo;
//        }
        StringBuilder result = new StringBuilder("检测结论：经检测，该部地基承载力为");
        List<DjczlbgBaDetailVo> collect = vo.getBaDetailVos().stream().filter(v -> BigDecimalUtil.isNotEmpty(v.getJiancjg())).collect(Collectors.toList());
        BigDecimal sum = collect.stream().map(DjczlbgBaDetailVo::getJiancjg).reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal divide = BigDecimalUtil.stpTrailZero(BigDecimalUtil.divide(sum, new BigDecimal(collect.size())));
        result.append(divide).append("kPa，符合设计文件要求。");
        vo.setJiancjl(result.toString());
        return vo;
    }
}
